package com.lanou.horo.zhuizhui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.lanou.horo.zhuizhui.R;
import com.lanou.horo.zhuizhui.adapter.BackGroundAdapter;
import com.lanou.horo.zhuizhui.entity.BackGroundItem;
import com.lanou.horo.zhuizhui.utility.customDialog.CustomProgressDialog;
import com.lanou.horo.zhuizhui.utility.clickInterface.BackgroundItemLisitener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/11/10.
 */
public class BackgroundActivity extends AppCompatActivity implements BackgroundItemLisitener, SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView;
    private BackGroundAdapter adapter;
    private RequestQueue queue;
    private ImageView backgroundBack;
    private SwipeRefreshLayout swipeRefreshWidget;
    private Handler handler;
    private int lastVisibleItem;
    private boolean isdialogshowing = false;
    private CustomProgressDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_background);
        swipeRefreshWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget);
        backgroundBack = (ImageView) findViewById(R.id.backgroundBack);
        backgroundBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        recyclerView = (RecyclerView) findViewById(R.id.backgroundRecyclerView);

        dialog = new CustomProgressDialog(this, "加载中...", R.anim.loding);

        dialog.setCanceledOnTouchOutside(false);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        swipeRefreshWidget.setRefreshing(true);
                        if (adapter.getEntities() != null) {
                            adapter.getEntities().clear();
                            initData();
                        }
                        break;
                }
            }
        };
        swipeRefreshWidget.setColorSchemeColors(0xff00aa00, 0xfffedcba, 0xff123456, 0xff654321);
        swipeRefreshWidget.setOnRefreshListener(this);
        swipeRefreshWidget.setProgressViewOffset(false, -30, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources()
                        .getDisplayMetrics()));

        swipeRefreshWidget.setProgressViewEndTarget(true, 100);
        adapter = new BackGroundAdapter(this);
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        manager.setOrientation(LinearLayout.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        adapter.setItemLisitener(this);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        initData();
    }

    private void initData() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        queue = Volley.newRequestQueue(this);
        String url = "http://api.lovebizhi.com/android_v3.php?a=category&spdy=1&device=generic%28Sony%20Xperia%20Z%20-%204.3%20-%20API%2018%20-%201080x1920%29&uuid=8e5822a044b20c6fbf90eac8ad5c9289&mode=1&client_id=1001&device_id=58987691&model_id=102&size_id=0&channel_id=1&screen_width=1080&screen_height=1920&bizhi_width=2160&bizhi_height=1920&version_code=75&language=zh-CN&mac=&original=0&tid=2 HTTP/1.1\n" +
                "User-Agent: LoveWallpaperHD/1001/3.8.3/1080*1920/18";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                BackGroundItem bgi = gson.fromJson(response, BackGroundItem.class);
                if (bgi != null) {
                    List<BackGroundItem.DataEntity> list = bgi.getData();
                    adapter.addPiclist(list);

                    swipeRefreshWidget.setRefreshing(false);
                    if (isdialogshowing == true) {
                        dialog.dismiss();
                        isdialogshowing = false;
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }

    @Override
    public void backgroundItemClick(BackGroundItem.DataEntity bd) {
        Intent intent = new Intent(this,UserInformationActivity.class);
        intent.putExtra("image", bd.getImage().getSmall());
        startActivity(intent);
        finish();
    }

    @Override
    public void onRefresh() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        handler.sendEmptyMessageDelayed(0, 3000);
    }
}

